package com.damon.g2048.view;

import java.util.ArrayList;
import java.util.List;

import android.content.Context;
import android.util.AttributeSet;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.widget.FrameLayout;

import com.damon.g2048.ConfigData;

public class AnimLayer extends FrameLayout {
	private List<Card> cards = new ArrayList<Card>();

	public AnimLayer(Context context, AttributeSet attrs, int defStyle) {
		super(context, attrs, defStyle);
	}

	public AnimLayer(Context context, AttributeSet attrs) {
		this(context, attrs, 0);
	}

	public AnimLayer(Context context) {
		this(context, null);
	}

	public void createMoveAnim(final Card from, final Card to, int fromX, int toX, int fromY, int toY) {
		final Card c = getCard(from.getNum());

		LayoutParams lp = new LayoutParams(ConfigData.CARD_WIDTH, ConfigData.CARD_WIDTH);
		lp.leftMargin = fromX * ConfigData.CARD_WIDTH;
		lp.topMargin = fromY * ConfigData.CARD_WIDTH;
		c.setLayoutParams(lp);

		if (to.getNum() <= 0) {
			to.getLabel().setVisibility(View.INVISIBLE);
		}
		TranslateAnimation ta = new TranslateAnimation(0, ConfigData.CARD_WIDTH * (toX - fromX), 0, ConfigData.CARD_WIDTH * (toY - fromY));
		ta.setDuration(200);
		ta.setInterpolator(getContext(), android.R.interpolator.accelerate_decelerate);
		ta.setAnimationListener(new Animation.AnimationListener() {

			@Override
			public void onAnimationStart(Animation animation) {
			}

			@Override
			public void onAnimationRepeat(Animation animation) {
			}

			@Override
			public void onAnimationEnd(Animation animation) {
				to.getLabel().setVisibility(View.VISIBLE);
				recycleCard(c);
			}
		});
		c.startAnimation(ta);

	}

	private void recycleCard(Card c) {
		c.setVisibility(View.INVISIBLE);
		c.setAnimation(null);
		cards.add(c);
	}

	private Card getCard(int num) {
		Card c = null;
		if (cards.size() > 0) {
			c = cards.remove(0);
		} else {
			c = new Card(getContext());
			addView(c);
		}
		c.setVisibility(View.VISIBLE);
		c.setNum(num);
		return c;
	}

}
